<?php
class omeauto_autoconfirm{
    
    function get_conditions(){
        return kernel::single('omeauto_auto')->get_conditions('autoconfirm');
    }
    
    function autoconfirm($order_id){
        $order_sdf = app::get('ome')->model('orders')->dump($order_id,"*",array("order_objects"=>array("*",array("order_items"=>array("*")))));
        //kernel::log('autoconfirm_sdf: '.serialize($order_sdf));
        //不进行自动确认条件：暂停、异常订单、销售单、已确认、已分派、失败订单、process_status(取消、余单撤销)、已作废(status:dead)订单
        $process_status = array('cancel','remain_cancel','splited','splitting');
        if ($order_sdf['order_type'] == 'sale' || $order_sdf['confirm'] == 'Y' || 
        $order_sdf['is_fail'] == 'true' || $order_sdf['pause'] == 'true' || $order_sdf['abnormal'] == 'true' ||  
        in_array($order_sdf['process_status'], $process_status) || $order_sdf['status'] == 'dead' || ($order_sdf['pay_status']!='1' && $order_sdf['shipping']['is_cod']=='false')){
            
            kernel::log('autoconfirm: false');
            return false;
        }
        kernel::log('autoconfirm: true');
        $oAutoconfirm = &app::get('omeauto')->model('autoconfirm');
        $oOrder = &app::get('ome')->model('orders');
        
        $rows = $oAutoconfirm->getList("*",array(),0,-1);
        if($rows){
            foreach($rows as $row){
                $flag = false;
                $config = $row['config'];
                if($config){
                    foreach($config as $condition=>$value){
                        $oCondition = kernel::single($condition);
                        foreach($value as $v){
                            $flag = $oCondition->validate($order_sdf,$v);
                            if(!$flag){
                                break;
                            }
                        }
                        if(!$flag){
                            break;
                        }
                    }
                }
                if($flag){
                    $branch = $row['branch'];
                    $dlycorp = $row['dlycorp'];
                    break;
                }
            }
            
            if($flag){
                $branch_id = $this->_get_branch($branch,$order_sdf);
                if($branch_id){
                    $corp_list = $this->_get_dlycorp_list($branch_id,$order_sdf);
                    if($corp_list){
                        $logi_id = $this->_get_dlycorp($dlycorp,$corp_list,$order_sdf);
                        if($logi_id){
                            $items = app::get('ome')->model('order_items')->getList("nums AS number,name AS product_name,bn,shop_product_id,product_id,item_id",array('order_id'=>$order_id,'delete'=>'false'),0,-1);
                            if ($items){
                                $num = array();
                                $order_items = array();
                                if (is_array($items))
                                foreach ($items as $v){
                                    $order_items[$v['item_id']] = $v;
                                    $num[$v['product_id']] += $v['number'];
                                    if ( isset( $num[$v['product_id']] ) ) {
                                        $v['number'] = $num[$v['product_id']];
                                        $new_delivery_items[$v['product_id']] = $v;
                                    }else {
                                        $new_delivery_items[$v['product_id']] = $v;
                                    }
                                    unset($new_delivery_items[$v['product_id']]['item_id']);
                                }
                            }else {
                                return false;
                            }
                            $data = array(
                                'delivery_items' => $new_delivery_items,
                                'branch_id' => $branch_id,
                                'logi_id' => $logi_id,
                            );
                            if (!app::get('ome')->model('orders')->confirm($order_id,true)) return false;
                            
                            if(app::get('ome')->model('delivery')->addDelivery($order_id,$data,array(),$order_items)){
                                $update = array('order_id'=>$order_id,'process_status'=>'splited');
                                app::get('ome')->model('orders')->save($update);
                            }
                            
                            return true;
                        }else{
                            return false;
                        }
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    private function _get_branch($branch,$order_sdf){
        //获取可从同一个仓库发货的所有仓库
        $db = kernel::database();
        $product_branch = array();
        foreach($order_sdf['order_objects'] as $object){
            foreach($object['order_items'] as $item){
                $branch_ids = $db->select("SELECT branch_id FROM sdb_ome_branch_product WHERE product_id=".$item['product_id']." AND store-store_freeze >=".$item['quantity']);
                if($branch_ids){
                    foreach($branch_ids as $branch_id){
                        $product_branch[$item['bn']][] = $branch_id['branch_id'];
                    }
                }else{
                    return false;
                }
            }
        }

        foreach($product_branch as $k=>$v){
            $intersect[] = "\$product_branch['".$k."']";
        }
        
        if(count($intersect) == 1){
            eval("\$branch_list=".$intersect[0].";");
        }else{
            eval("\$branch_list=array_intersect(".implode(",",$intersect).");");
        }
        
        $branch_candidate = kernel::single($branch)->get_branch($order_sdf,$branch_list);   //获取候选的仓库id数组
        
        if($branch_candidate){
            if(is_array($branch_candidate)){
                if(count($branch_candidate) == 1){
                    return $branch_candidate[0];
                }else{
                    return false;
                }
            }else if(is_numeric($branch_candidate)){
                return $branch_candidate;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    private function _get_dlycorp($dlycorp,$corp_list,$order_sdf){
        $dlycorp_candidate = kernel::single($dlycorp)->get_dlycorp($corp_list,$order_sdf);
        
        if($dlycorp_candidate){
            if(is_array($dlycorp_candidate)){
                if(count($dlycorp_candidate) == 1){
                    return $dlycorp_candidate[0];
                }else{
                    return false;
                }
            }else if(is_numeric($dlycorp_candidate)){
                return $dlycorp_candidate;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    
    private function _get_dlycorp_list($branch_id,$order){
        $oBranch = &app::get('ome')->model('branch');
        $list = $oBranch->get_corp($branch_id);
        $dlyCorpObj = &app::get('ome')->model('dly_corp');
        $corp_region = $dlyCorpObj->get_corp_region();

        list($pkg,$regions,$region_id) = explode(':',$order['consignee']['area']);
        $order_region[] = $region_id;
        $oRegion = &app::get('ectools')->model('regions');
        $region = $oRegion->dump($region_id,"local_name,region_path");
        
        $region_path = explode(",",$region['region_path']);
        array_shift($region_path);
        array_pop($region_path);
        array_pop($region_path);
        
        if($region_path){
            foreach($region_path as $id){
                if(!in_array($id,$order_region)){
                    $order_region[] = $id;
                }
            }
        }

        if($list){
            $ret = array();
            foreach($list as $v){
                for($i=0;$i<count($order_region);$i++){
                    if(is_array($corp_region[$v['corp_id']]) && in_array($order_region[$i],$corp_region[$v['corp_id']])){
                        $ret[] = $v['corp_id'];
                        break;
                    }elseif(!isset($corp_region[$v['corp_id']]) && $v['corp_id']){
                        $ret[] = $v['corp_id'];
                        break;
                    }
                }
            }
            return $ret;
        }else{
            return false;
        }
    }
}